package com.wzdigit.wms.wms.service.inv.count;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wzdigit.framework.Shift;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicSimpleCodeRuleApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.wms.basic.client.Pager;
import com.wzdigit.wms.basic.client.PagerInfo;
import com.wzdigit.wms.basic.client.response.Result;
import com.wzdigit.wms.basic.domain.basic.*;
import com.wzdigit.wms.basic.domain.inventory.Lotno;
import com.wzdigit.wms.basic.domain.util.ExportExcleDTO;
import com.wzdigit.wms.basic.enums.inventory.count.approve.InvAprResultEnum;
import com.wzdigit.wms.basic.enums.inventory.count.header.*;
import com.wzdigit.wms.basic.mapper.core.basic.*;
import com.wzdigit.wms.basic.mapper.core.inventory.LotnoMapper;
import com.wzdigit.wms.basic.util.HttpSessionUtil;
import com.wzdigit.wms.common.entity.ExcelExportConfig;
import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.common.utils.ExportExcelUtils;
import com.wzdigit.wms.common.utils.HttpExcel;
import com.wzdigit.wms.wms.client.request.inv.count.CountHeaderInsertDto;
import com.wzdigit.wms.wms.client.request.inv.count.CountHeaderRequest;
import com.wzdigit.wms.wms.client.request.inv.count.CountScopeDto;
import com.wzdigit.wms.wms.client.request.inv.count.CountScopeInfoDto;
import com.wzdigit.wms.wms.client.request.inv.count.dto.ExportSkuDto;
import com.wzdigit.wms.wms.client.response.inv.count.CountHeaderResponse;
import com.wzdigit.wms.wms.domain.inv.count.InvCountHeader;
import com.wzdigit.wms.wms.domain.inv.count.InvCountScope;
import com.wzdigit.wms.wms.mapper.inv.count.InvCountHeaderMapper;
import com.wzdigit.wms.wms.mapper.inv.count.InvCountScopeMapper;
import com.wzdigit.wms.wms.service.inv.count.util.InvStarUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 盘点单新增BS Service
 * Created by zyf on 2021/10/9 9:53
 */
@Slf4j
@Service
public class InvCountService {
    private static final String INV_NO="INV_NO";
    private static final String STAR="*";

    @Value(value = "${default_owner.code}")
    private String DEFAULT_OWNER;
    @Value(value = "${default_owner.name}")
    private String DEFAULT_OWNER_NAME;


    @Autowired
    private InvCountHeaderMapper invCountHeaderMapper;
    @Autowired
    private InvCountScopeMapper invCountScopeMapper;
    @Autowired
    private ZoneMapper zoneMapper;
    @Autowired
    private LocationMapper locationMapper;
    @Autowired
    private LotnoMapper lotnoMapper;
    @Autowired
    private SkuCateMapper skuCateMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;

    @Autowired
    private InvStarUtil invStarUtil;
    @Autowired
    private ExportExcelUtils exportExcelUtils;

    @Reference(version = "${dubbo.consumers.basic.simple.code.rule.api:1.0.0}", check = false)
    private BasicSimpleCodeRuleApi basicSimpleCodeRuleApi;
    @Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
    private BasicDataItemDetailApi dataItemDetailApi;


    //分页查询盘点单头
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<CountHeaderResponse>> searchCountHeader(CountHeaderRequest search, Pager<?> pager){
        Page<CountHeaderResponse> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        PagerInfo<List<CountHeaderResponse>> pagerInfo = new PagerInfo<>();
        List<CountHeaderResponse> datas = this.selectOrderBlotter(search);
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //导出盘点单头
    @Transactional
    public void exportCountHeader(
            CountHeaderRequest search, HttpServletRequest servletRequest,
            HttpServletResponse servletResponse)  throws Exception{
        ServletOutputStream out = null;
        XSSFWorkbook workbook = null;
        try {
            List<CountHeaderResponse> resultDatas = this.selectOrderBlotter(search);
            List<ExcelExportConfig> configs = new ArrayList<>();
            configs.add(new ExcelExportConfig("盘点单号", "countNo", 120));
            configs.add(new ExcelExportConfig("盘点单名称", "countName", 120));
            configs.add(new ExcelExportConfig("盘点类型", "countTypeStr", 120));
            configs.add(new ExcelExportConfig("状态", "headerStatusStr", 120));
            configs.add(new ExcelExportConfig("盘点日期", "countDate", 120));
            configs.add(new ExcelExportConfig("原因", "reson", 120));
            configs.add(new ExcelExportConfig("原因描述", "resonDesc", 120));
            configs.add(new ExcelExportConfig("盘点结果", "result", 120));
            configs.add(new ExcelExportConfig("来源", "source", 120));
            configs.add(new ExcelExportConfig("货主", "owner", 120));
            configs.add(new ExcelExportConfig("仓库", "whsName", 120));
            configs.add(new ExcelExportConfig("指定盘点人", "countUser", 120));
            configs.add(new ExcelExportConfig("备注", "comments", 120));
            configs.add(new ExcelExportConfig("创建时间", "createTime", 120));
            configs.add(new ExcelExportConfig("创建人", "createUser", 120));
            configs.add(new ExcelExportConfig("修改时间", "modifyTime", 120));
            configs.add(new ExcelExportConfig("修改人", "modifyUser", 120));
            configs.add(new ExcelExportConfig("审核时间", "resultAprTime", 120));
            configs.add(new ExcelExportConfig("审核人", "resultAprUser", 120));
            configs.add(new ExcelExportConfig("审核意见", "aprResultStr", 120));
            workbook = HttpExcel.newListToExcel(resultDatas, configs);
            String userAgent = servletRequest.getHeader("USER-AGENT");
            String fileName = "订单流水报表";
            if (userAgent.contains("Mozilla")) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "utf8");
            }
            servletResponse.setContentType("application/octet-stream");
            servletResponse.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".xlsx");
            servletResponse.flushBuffer();
            out = servletResponse.getOutputStream();
            workbook.write(out);
        }catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
            if(workbook != null) {
                workbook.close();
            }
        }
    }

    //测试
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void testEsport(
            CountHeaderRequest search, HttpServletRequest servletRequest,
            HttpServletResponse servletResponse)  throws Exception{
        ServletOutputStream out = null;

        List<CountHeaderResponse> resultDatas = this.selectOrderBlotter(search);
        /*String[] headers=new String[]{"盘点单头ID","盘点单号","盘点单名称",
                "盘点类型1","盘点类型2","状态1","状态2","盘点日期","原因","原因描述","盘点结果","来源",
                "货主","仓库","指定盘点人","备注","创建时间","创建人","修改时间","修改人",
                "审核时间","审核人","审核意见1","审核意见2"};*/

        System.out.println(resultDatas.get(0).getCreateTime()+"----------");

        String[] headers=new String[]{"盘点单头ID","盘点单号","盘点单名称",
                "盘点类型1","盘点类型2","状态1","状态2","盘点日期","原因","原因描述","盘点结果","来源",
                "货主","仓库","指定盘点人","备注","创建时间","创建人","修改时间","修改人"};


        String userAgent = servletRequest.getHeader("USER-AGENT");
        String fileName = "订单流水报表";
        if (userAgent.contains("Mozilla")) {
            fileName = new String(fileName.getBytes(), "ISO8859-1");
        } else {
            fileName = URLEncoder.encode(fileName, "utf8");
        }
        servletResponse.setContentType("application/octet-stream");
        servletResponse.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".xlsx");
        servletResponse.flushBuffer();
        out = servletResponse.getOutputStream();

        List<ExportExcleDTO> list=new ArrayList<>();
        ExportExcleDTO dto=new ExportExcleDTO();
        dto.setTitle("11");
        dto.setHeaders(headers);
        dto.setDataSet(resultDatas);
        dto.setFormatType("yyyyMMdd");
        ExportExcleDTO dto2=new ExportExcleDTO();
        dto2.setTitle("22");
        dto2.setHeaders(headers);
        dto2.setDataSet(resultDatas);
        dto2.setFormatType("yyyyMMdd");
        list.add(dto);list.add(dto2);


        exportExcelUtils.exportExcel(list,out);
    }

    //查询盘点单头信息，复用
    public List<CountHeaderResponse> selectOrderBlotter(CountHeaderRequest search){
        //查询默认货主

        if (CollectionUtil.isEmpty(search.getHeaderIds())){
            search.setHeaderIds(null);
        }
        if (search.getCountBegin()!=null){
            search.setCountTimeBegin(new Date(search.getCountBegin()));
        }
        if (search.getCountEnd()!=null){
            if (search.getCountEnd().equals(search.getCountBegin())){
                Date date=new Date(search.getCountEnd());
                Calendar   calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
                date=calendar.getTime(); //这个时间就是日期往后推一天的结果

                search.setCountTimeEnd(date);
            }else {
                Date date=new Date(search.getCountEnd());
                search.setCountTimeEnd(date);
            }
        }
        List<CountHeaderResponse> datas = invCountHeaderMapper.selcetCountHeaders(search);
        for (CountHeaderResponse data : datas) {
            if (data.getResultInt()!=null){
                InvHeaderResultEnum headerResultEnum = InvHeaderResultEnum.getEnumByCode(data.getResultInt());
                if (headerResultEnum!=null){
                    data.setResult(headerResultEnum.enumName);
                }
            }
            if (data.getCountType()!=null){
                InvHeaderTypeEnum invType = InvHeaderTypeEnum.getEnumByCode(data.getCountType());
                if (invType!=null){
                    data.setCountTypeStr(invType.enumName);
                }
            }
            if (data.getHeaderStatus()!=null){
                InvHeaderStatusEnum invStatus = InvHeaderStatusEnum.getEnumByCode(data.getHeaderStatus());
                if (invStatus!=null){
                    data.setHeaderStatusStr(invStatus.enumName);
                }
            }
            if (data.getResonCode()!=null){
                InvResonEnum invResonEnum = InvResonEnum.getEnumByCode(data.getResonCode());
                if (invResonEnum!=null){
                    data.setReson(invResonEnum.getEnumName());
                }
            }
            data.setOwner(DEFAULT_OWNER_NAME);
            if (data.getAprResult()!=null){
                InvAprResultEnum invAprResult = InvAprResultEnum.getEnumByCode(data.getAprResult());
                if (invAprResult!=null){
                    data.setAprResultStr(invAprResult.enumName);
                }
            }
        }
        return datas;
    }

    //查询盘点范围
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<InvCountScope>> searchCountScope(BigDecimal headerId, Pager<?> pager){
        Page<InvCountScope> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        PagerInfo<List<InvCountScope>> pagerInfo = new PagerInfo<>();
        pagerInfo.setTotalCount(page.getTotal());
        List<InvCountScope> datas = invCountScopeMapper.selectList(new QueryWrapper<InvCountScope>().eq("INV_COUNT_HEADER_ID", headerId));
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //编辑前查询盘点主档信息
    public CountHeaderInsertDto searchHeaderDto(BigDecimal headerId){
        CountHeaderInsertDto resultDto=new CountHeaderInsertDto();
        InvCountHeader header = invCountHeaderMapper.
                selectOne(new QueryWrapper<InvCountHeader>().eq("INV_COUNT_HEADER_ID", headerId));
        if (header==null){
            return resultDto;
        }
        resultDto.setInvHeaderId(headerId);
        resultDto.setInvCountNo(header.getInvCountNo());
        resultDto.setInvCountName(header.getInvCountName());
        resultDto.setInvCountType(header.getInvCountType());
        resultDto.setCountBy(header.getCountBy());
        resultDto.setSource(header.getSource());
        resultDto.setReasonCode(header.getReasonCode());
        resultDto.setReasonDesc(header.getReasonDesc());
        resultDto.setCountGranularity(header.getCountGranularity());
        resultDto.setCountMode(header.getCountMode());
        resultDto.setWhsId(header.getWhsId());
        resultDto.setIncludeEmpty(header.getIncludeEmpty());
        resultDto.setDynamicInventory(header.getDynamicInventory());
        resultDto.setBlindCount(header.getBlindCount());
        resultDto.setDispKeyAttr(header.getDispKeyAttr());
        resultDto.setSnScanMode(header.getSnScanMode());
        resultDto.setComments(header.getComments());
        resultDto.setStatus(header.getStatus());
        resultDto.setIncludeNoPutaway(header.getIncludeNoPutaway());

        resultDto.setInvCountDate(header.getInvCountDate().getTime());
        if (header.getReleaseTime()!=null){
            resultDto.setReleaseTime(header.getReleaseTime().getTime());
        }


        if (resultDto.getWhsId()!=null){
            Warehouse warehouse = warehouseMapper.selectOne(new QueryWrapper<Warehouse>().eq("WHS_ID", resultDto.getWhsId()));
            if (warehouse!=null){
                resultDto.setWhsCode(warehouse.getWhsCode());
            }
        }



        return resultDto;
    }

    //保存盘点单【更新/新增】
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public CountHeaderInsertDto saveCountHeader(CountHeaderInsertDto dto, HttpServletRequest servletRequest) throws Exception{


        if (dto.getInvCountName()==null){
            Shift.fatal("盘点单名称不能为空!");
        }
        if (dto.getInvCountType()==null){
            Shift.fatal("盘点类型不能为空!");
        }
        if (dto.getStatus()==null){
            Shift.fatal("盘点单状态不能为空!");
        }
        if (dto.getSource()==null){
            Shift.fatal("盘点单来源不能为空!");
        }
        if (dto.getReasonCode()==null){
            Shift.fatal("原因不能为空!");
        }
        if (dto.getWhsCode()==null){
            Shift.fatal("盘点单仓库不能为空!");
        }
        Warehouse warehouse = warehouseMapper.selectOne(new QueryWrapper<Warehouse>().eq("WHS_CODE", dto.getWhsCode()));
        if (warehouse==null){
            Shift.fatal("查无仓库["+dto.getWhsCode()+"]");
        }
        dto.setWhsId(warehouse.getWhsId());
        if (dto.getIncludeEmpty()==null){
            Shift.fatal("是否包含空库位不能为空!");
        }
        if (dto.getIncludeNoPutaway()==null){
            Shift.fatal("是否非上架库存不能为空!");
        }
        if (dto.getDynamicInventory()==null){
            Shift.fatal("是否动态库存不能为空!");
        }
        if (dto.getBlindCount()==null){
            Shift.fatal("是否盲盘不能为空!");
        }
        if (dto.getDispKeyAttr()==null){
            Shift.fatal("是否显示关键批次属性不能为空!");
        }
        if (dto.getSnScanMode()==null){
            Shift.fatal("SN扫码方式不能为空!");
        }
        BigDecimal invHeaderId = dto.getInvHeaderId();

        InvCountHeader header=new InvCountHeader();
        this.setHeader(dto,header);
        String invNo = dto.getInvCountNo();
        if (invNo==null){
            invNo=basicSimpleCodeRuleApi.GenerateCode(INV_NO);
        }
        if (invHeaderId!=null){
            InvCountHeader checkHeader = invCountHeaderMapper.selectOne(new QueryWrapper<InvCountHeader>().eq("INV_COUNT_HEADER_ID", invHeaderId));
//            if (!checkHeader.getStatus().equals(InvHeaderStatusEnum.CREATE.code)&&!checkHeader.getStatus().equals(InvHeaderStatusEnum.APPROVED.code)){
//                Shift.fatal("非新建/审核的盘点单无法更新!");
//            }
            List<InvCountScope> scopeList = invCountScopeMapper.selectList(
                    new QueryWrapper<InvCountScope>().eq("INV_COUNT_HEADER_ID", invHeaderId));
            if (!CollectionUtil.isEmpty(scopeList)){
                if (!checkHeader.getIncludeEmpty().equals(dto.getIncludeEmpty())){
                    Shift.fatal("已选择盘点范围无法更新[是否包含空库位]");
                }
                if (!checkHeader.getIncludeNoPutaway().equals(dto.getIncludeNoPutaway())){
                    Shift.fatal("已选择盘点范围无法更新[是否包含非上架库存]");
                }
                if (!checkHeader.getWhsId().equals(dto.getWhsId())){
                    Shift.fatal("已选择盘点范围无法更新[仓库]");
                }
                if (!checkHeader.getCountMode().equals(dto.getCountMode())){
                    Shift.fatal("已选择盘点范围无法更新[盘点方式]");
                }
            }
        }
        header.setInvCountNo(invNo);
        //如果货主为空，则给默认货主
        if (header.getOwner()==null){
            //设置默认货主
            DataItemDetailDTO dataItem=new DataItemDetailDTO();
            List<DataItemDetailDTO> dataItemDetailByCode = dataItemDetailApi.getDataItemDetailByCode(DEFAULT_OWNER);
            for (DataItemDetailDTO dataItemDetailDTO : dataItemDetailByCode) {
                if (DEFAULT_OWNER.equals(dataItemDetailDTO.getItemCode())){
                    dataItem=dataItemDetailDTO;
                }
            }
            int ownerId = (dataItem == null || dataItem.getItemValue() == null ? 0 : Integer.parseInt(dataItem.getItemValue()));
            header.setOwner(ownerId);
        }

        if (invHeaderId==null){

            header.setCreateTime(new Date());
            header.setCreateUser(HttpSessionUtil.getLoginName(servletRequest));
            invCountHeaderMapper.insert(header);
        }else {
            header.setModifyTime(new Date());
            header.setModifyUser(HttpSessionUtil.getLoginName(servletRequest));
            invCountHeaderMapper.updateHeaderInfo(header);
        }

        CountHeaderInsertDto resultDto=new CountHeaderInsertDto();
        resultDto.setInvCountNo(invNo);

        resultDto.setInvHeaderId(invCountHeaderMapper.selectOne(new QueryWrapper<InvCountHeader>().eq("INV_COUNT_NO",invNo)).getInvCountHeaderId());

        return resultDto;
    }

    private void setHeader(CountHeaderInsertDto dto, InvCountHeader header) {
        header.setInvCountHeaderId(dto.getInvHeaderId());
        header.setInvCountName(dto.getInvCountName());
        header.setInvCountType(dto.getInvCountType());
        header.setInvCountDate(new Date(dto.getInvCountDate()));
        header.setCountBy(dto.getCountBy());
        header.setSource(dto.getSource());
        if (dto.getReleaseTime()!=null){
            header.setReleaseTime(new Date(dto.getReleaseTime()));
        }
        header.setReasonCode(dto.getReasonCode());
        header.setReasonDesc(dto.getReasonDesc());
        header.setCountGranularity(dto.getCountGranularity());
        header.setCountMode(dto.getCountMode());

        header.setWhsId(dto.getWhsId());
        header.setIncludeEmpty(dto.getIncludeEmpty());
        header.setDynamicInventory(dto.getDynamicInventory());
        header.setBlindCount(dto.getBlindCount());
        header.setDispKeyAttr(dto.getDispKeyAttr());
        header.setSnScanMode(dto.getSnScanMode());
        header.setComments(dto.getComments());
        header.setStatus(dto.getStatus());
        header.setIncludeNoPutaway(dto.getIncludeNoPutaway());
        header.setInvCountNo(dto.getInvCountNo());
    }

    //查询库区
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<Zone>> searchCountZone(CountScopeDto dto,Pager<?> pager) throws Exception{
        Integer whsId=dto.getWhsId();

        Integer beginzoneId=null;
        Integer endZoneId=null;
        if (dto.getBegin()!=null){
            Zone zone = zoneMapper.selectOne(
                    new QueryWrapper<Zone>().eq("ZONE_CODE", dto.getBegin()));
            if (zone==null){
                Shift.fatal("查无对应库区!");
            }
            beginzoneId=zone.getZoneId();
        }
        if (dto.getEnd()!=null){
            Zone zone = zoneMapper.selectOne(
                    new QueryWrapper<Zone>().eq("ZONE_CODE", dto.getEnd()));
            if (zone==null){
                Shift.fatal("查无对应库区!");
            }
            endZoneId=zone.getZoneId();
        }
        Integer isEmpty=dto.getIsEmpty();

        Integer begin=null;Integer end=null;
        if (beginzoneId!=null&&endZoneId!=null){
            if (beginzoneId>endZoneId){
                begin=endZoneId;end=beginzoneId;
            }else {
                end=endZoneId;begin=beginzoneId;
            }
        }
        Boolean emptyFlag=true;
        if (isEmpty!=null){
            if (isEmpty.equals(InvIsEmptyEnum.YES.code)){
                emptyFlag=false;
            }
        }


        Page<Zone> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        PagerInfo<List<Zone>> pagerInfo = new PagerInfo<>();
        List<Zone> datas = invCountHeaderMapper.selectCoutnZones(whsId,begin,end,emptyFlag);
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //查询库位
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<Location>> searchCountLoc(CountScopeDto dto, Pager<?> pager) throws Exception{
        Integer whsId=dto.getWhsId();
        List<String> zoneCodes=dto.getZoneCodes();
        zoneCodes=invStarUtil.contverStar(zoneCodes);

        Integer beginLocId=null;
        Integer endLocId=null;
        Integer isEmpty=dto.getIsEmpty();

        if (dto.getBegin()!=null){
            Location location = locationMapper.selectOne(
                    new QueryWrapper<Location>().eq("LOC_CODE", dto.getBegin()));
            if (location==null){
                Shift.fatal("查无对应库位!");
            }
            beginLocId=location.getLocId();
        }
        if (dto.getEnd()!=null){
            Location location = locationMapper.selectOne(
                    new QueryWrapper<Location>().eq("LOC_CODE", dto.getEnd()));
            if (location==null){
                Shift.fatal("查无对应库位!");
            }
            endLocId=location.getLocId();
        }

        Integer begin=null;Integer end=null;
        if (beginLocId!=null&&endLocId!=null){
            if (beginLocId>endLocId){
                begin=endLocId;end=beginLocId;
            }else {
                end=endLocId;begin=beginLocId;
            }
        }
        Boolean emptyFlag=true;
        if (isEmpty!=null){
            if (isEmpty.equals(InvIsEmptyEnum.YES.code)){
                emptyFlag=false;
            }
        }

        try {
            zoneCodes=invStarUtil.getZones(zoneCodes,whsId,emptyFlag);
            if (CollectionUtil.isEmpty(zoneCodes)){
                Shift.fatal("查无对应库区!");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }

        Page<Location> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        PagerInfo<List<Location>> pagerInfo = new PagerInfo<>();
        List<Location> datas = invCountHeaderMapper.selectCoutnLocs(zoneCodes,begin,end,emptyFlag);
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //仅成品：查询批次号
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<Lotno>> searchCountLotno(CountScopeDto dto,
                                                   Pager<?> pager) throws Exception{
        Integer whsId=dto.getWhsId();
        List<String> zoneCodes=dto.getZoneCodes();
        List<String> locCodes=dto.getLocCodes();
        zoneCodes=invStarUtil.contverStar(zoneCodes);
        locCodes=invStarUtil.contverStar(locCodes);

        Integer beginLtId=null;
        Integer endLtId=null;
        Integer isEmpty=dto.getIsEmpty();
        Integer isPut=dto.getIsPut();

        if (dto.getBegin()!=null){
            Lotno lotno = lotnoMapper.selectOne(
                    new QueryWrapper<Lotno>().eq("LOTNO", dto.getBegin()));
            if (lotno==null){
                Shift.fatal("查无对应批次!");
            }
            beginLtId=lotno.getLotnoId();
        }
        if (dto.getEnd()!=null){
            Lotno lotno = lotnoMapper.selectOne(
                    new QueryWrapper<Lotno>().eq("LOTNO", dto.getEnd()));
            if (lotno==null){
                Shift.fatal("查无对应批次!");
            }
            endLtId=lotno.getLotnoId();
        }

        Integer begin=null;Integer end=null;
        if (beginLtId!=null&&endLtId!=null){
            if (beginLtId>endLtId){
                begin=endLtId;end=beginLtId;
            }else {
                end=endLtId;begin=beginLtId;
            }
        }
        Boolean emptyFlag=true;
        if (isEmpty!=null){
            if (isEmpty.equals(InvIsEmptyEnum.YES.code)){
                emptyFlag=false;
            }
        }
        Boolean putFlag=false;
        if (isPut!=null){
            if (isPut.equals(InvIsPutEnum.YES.code)){
                putFlag=true;
            }
        }

        try {
            zoneCodes=invStarUtil.getZones(zoneCodes,whsId,emptyFlag);
            if (CollectionUtil.isEmpty(zoneCodes)){
                Shift.fatal("查无对应库区!");
            }
            locCodes=invStarUtil.getLoc(zoneCodes,locCodes,emptyFlag);
            if (CollectionUtil.isEmpty(locCodes)){
                Shift.fatal("查无对应库位!");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }

        Page<Lotno> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        PagerInfo<List<Lotno>> pagerInfo = new PagerInfo<>();
        List<Lotno> datas = invCountHeaderMapper.selectCoutnLotnos(whsId,locCodes,begin,end,emptyFlag,putFlag);
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //选择物料分类
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<SkuCate>> searchCountSkuCate(CountScopeDto dto, Pager<?> pager) throws Exception{
        Integer whsId=dto.getWhsId();
        List<String> zoneCodes=dto.getZoneCodes();
        List<String> locCodes=dto.getLocCodes();
        List<String> lotnos=dto.getLotnos();
        zoneCodes=invStarUtil.contverStar(zoneCodes);
        locCodes=invStarUtil.contverStar(locCodes);
        lotnos=invStarUtil.contverStar(lotnos);

        Integer beginCateId=null;
        Integer endCateId=null;
        Integer isEmpty=dto.getIsEmpty();
        Integer isPut=dto.getIsPut();

        if (dto.getBegin()!=null){
            SkuCate skuCate = skuCateMapper.selectOne(
                    new QueryWrapper<SkuCate>().eq("SKU_CATE_CODE", dto.getBegin()));
            if (skuCate==null){
                Shift.fatal("查无对应分类!");
            }
            beginCateId=skuCate.getSkuCateId();
        }
        if (dto.getEnd()!=null){
            SkuCate skuCate = skuCateMapper.selectOne(
                    new QueryWrapper<SkuCate>().eq("SKU_CATE_CODE", dto.getEnd()));
            if (skuCate==null){
                Shift.fatal("查无对应分类!");
            }
            endCateId=skuCate.getSkuCateId();
        }

        Integer begin=null;Integer end=null;
        if (beginCateId!=null&&endCateId!=null){
            if (beginCateId>endCateId){
                begin=endCateId;end=beginCateId;
            }else {
                end=endCateId;begin=beginCateId;
            }
        }
        Boolean emptyFlag=true;
        if (isEmpty!=null){
            if (isEmpty.equals(InvIsEmptyEnum.YES.code)){
                emptyFlag=false;
            }
        }
        Boolean putFlag=false;
        if (isPut!=null){
            if (isPut.equals(InvIsPutEnum.YES.code)){
                putFlag=true;
            }
        }

        try {
            zoneCodes=invStarUtil.getZones(zoneCodes,whsId,emptyFlag);
            if (CollectionUtil.isEmpty(zoneCodes)){
                Shift.fatal("查无对应库区!");
            }
            locCodes=invStarUtil.getLoc(zoneCodes,locCodes,emptyFlag);
            if (CollectionUtil.isEmpty(locCodes)){
                Shift.fatal("查无对应库位!");
            }
            lotnos=invStarUtil.getLotno(whsId,locCodes,lotnos,emptyFlag,putFlag);
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }

        Page<SkuCate> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        PagerInfo<List<SkuCate>> pagerInfo = new PagerInfo<>();
        List<SkuCate> datas = invCountHeaderMapper.selectCoutnCates(whsId,locCodes,lotnos,begin,end,emptyFlag,putFlag);
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //查询物料
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<Sku>> searchCountSku(CountScopeDto dto,Pager<?> pager) throws Exception{
        Integer whsId=dto.getWhsId();
        List<String> zoneCodes=dto.getZoneCodes();
        List<String> locCodes=dto.getLocCodes();
        List<String> lotnos=dto.getLotnos();
        List<String> cateCodes=dto.getCateCodes();
        zoneCodes=invStarUtil.contverStar(zoneCodes);
        locCodes=invStarUtil.contverStar(locCodes);
        lotnos=invStarUtil.contverStar(lotnos);
        cateCodes=invStarUtil.contverStar(cateCodes);

        Integer beginSkuId=null;
        Integer endSkuId=null;
        Integer isEmpty=dto.getIsEmpty();
        Integer isPut=dto.getIsPut();

        if (dto.getBegin()!=null){
            Sku sku = skuMapper.selectOne(
                    new QueryWrapper<Sku>().eq("SKU_CODE", dto.getBegin()));
            if (sku==null){
                Shift.fatal("查无对应物料编码!");
            }
            beginSkuId=sku.getSkuId();
        }
        if (dto.getEnd()!=null){
            Sku sku = skuMapper.selectOne(
                    new QueryWrapper<Sku>().eq("SKU_CODE", dto.getEnd()));
            if (sku==null){
                Shift.fatal("查无对应物料编码!");
            }
            endSkuId=sku.getSkuId();
        }

        Integer begin=null;Integer end=null;
        if (beginSkuId!=null&&endSkuId!=null){
            if (beginSkuId>endSkuId){
                begin=endSkuId;end=beginSkuId;
            }else {
                end=endSkuId;begin=beginSkuId;
            }
        }
        Boolean emptyFlag=true;
        if (isEmpty!=null){
            if (isEmpty.equals(InvIsEmptyEnum.YES.code)){
                emptyFlag=false;
            }
        }
        Boolean putFlag=false;
        if (isPut!=null){
            if (isPut.equals(InvIsPutEnum.YES.code)){
                putFlag=true;
            }
        }

        try {
            zoneCodes=invStarUtil.getZones(zoneCodes,whsId,emptyFlag);
            if (CollectionUtil.isEmpty(zoneCodes)){
                Shift.fatal("查无对应库区!");
            }
            locCodes=invStarUtil.getLoc(zoneCodes,locCodes,emptyFlag);
            if (CollectionUtil.isEmpty(locCodes)){
                Shift.fatal("查无对应库位!");
            }
            lotnos=invStarUtil.getLotno(whsId,locCodes,lotnos,emptyFlag,putFlag);
            cateCodes=invStarUtil.getCate(whsId,locCodes,lotnos,cateCodes,emptyFlag,putFlag);
            if (CollectionUtil.isEmpty(cateCodes)){
                Shift.fatal("查无对应物料分类!");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }

        Page<Sku> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        PagerInfo<List<Sku>> pagerInfo = new PagerInfo<>();
        List<Sku> datas = invCountHeaderMapper.selectCoutnSku(whsId,locCodes,lotnos,cateCodes,begin,end,emptyFlag,putFlag);
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public List<Sku> exortSku(CountScopeDto dto,MultipartFile file) throws Exception{

        log.info("["+dto.getCountHeaderId()+"]"+"盘点范围导入------------");
        System.out.println(file);
        //已经勾选的物料编码
        List<String> hasSkuCodes = dto.getHasSkuCodes();

        List<ExportSkuDto> exportSkuDtos = null;
        try {
            InputStream inputStream = file.getInputStream();
            String[] properties = { "skuCode"};
            exportSkuDtos = HttpExcel.importExcel(inputStream, ExportSkuDto.class, properties);
        } catch (Exception e) {
            // 模板错误，请确认
            e.printStackTrace();
            Shift.fatal(StatusCode.IMPORT_DATA_ERROR);
        }
        if (exportSkuDtos == null || exportSkuDtos.size() == 0) {
            // 该模板数据为空
            Shift.fatal(StatusCode.IMPORT_DATA_NULL);
        }

        List<String> exportSkuCodes = exportSkuDtos.stream().map(t -> t.getSkuCode()).distinct().collect(Collectors.toList());

        Integer whsId=dto.getWhsId();
        List<String> zoneCodes=dto.getZoneCodes();
        List<String> locCodes=dto.getLocCodes();
        List<String> lotnos=dto.getLotnos();
        List<String> cateCodes=dto.getCateCodes();
        zoneCodes=invStarUtil.contverStar(zoneCodes);
        locCodes=invStarUtil.contverStar(locCodes);
        lotnos=invStarUtil.contverStar(lotnos);
        cateCodes=invStarUtil.contverStar(cateCodes);

        Integer beginSkuId=null;
        Integer endSkuId=null;
        Integer isEmpty=dto.getIsEmpty();
        Integer isPut=dto.getIsPut();

        if (dto.getBegin()!=null){
            Sku sku = skuMapper.selectOne(
                    new QueryWrapper<Sku>().eq("SKU_CODE", dto.getBegin()));
            if (sku==null){
                Shift.fatal("查无对应物料编码!");
            }
            beginSkuId=sku.getSkuId();
        }
        if (dto.getEnd()!=null){
            Sku sku = skuMapper.selectOne(
                    new QueryWrapper<Sku>().eq("SKU_CODE", dto.getEnd()));
            if (sku==null){
                Shift.fatal("查无对应物料编码!");
            }
            endSkuId=sku.getSkuId();
        }

        Integer begin=null;Integer end=null;
        if (beginSkuId!=null&&endSkuId!=null){
            if (beginSkuId>endSkuId){
                begin=endSkuId;end=beginSkuId;
            }else {
                end=endSkuId;begin=beginSkuId;
            }
        }
        Boolean emptyFlag=true;
        if (isEmpty!=null){
            if (isEmpty.equals(InvIsEmptyEnum.YES.code)){
                emptyFlag=false;
            }
        }
        Boolean putFlag=false;
        if (isPut!=null){
            if (isPut.equals(InvIsPutEnum.YES.code)){
                putFlag=true;
            }
        }

        try {
            zoneCodes=invStarUtil.getZones(zoneCodes,whsId,emptyFlag);
            if (CollectionUtil.isEmpty(zoneCodes)){
                Shift.fatal("查无对应库区!");
            }
            locCodes=invStarUtil.getLoc(zoneCodes,locCodes,emptyFlag);
            if (CollectionUtil.isEmpty(locCodes)){
                Shift.fatal("查无对应库位!");
            }
            lotnos=invStarUtil.getLotno(whsId,locCodes,lotnos,emptyFlag,putFlag);
            cateCodes=invStarUtil.getCate(whsId,locCodes,lotnos,cateCodes,emptyFlag,putFlag);
            if (CollectionUtil.isEmpty(cateCodes)){
                Shift.fatal("查无对应物料分类!");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }

        List<Sku> allSku = invCountHeaderMapper.selectCoutnSku(whsId,locCodes,lotnos,cateCodes,begin,end,emptyFlag,putFlag);
        if (CollectionUtil.isEmpty(allSku)){
            Shift.fatal("查无对应物料!");
        }
        Map<String, List<Sku>> allSkuMap = allSku.stream().collect(Collectors.groupingBy(Sku::getSkuCode));

        //用于去重物料编码
        List<Sku> datas=new ArrayList<>();
        for (String exportSkuCode : exportSkuCodes) {
            if (hasSkuCodes!=null){
                if (hasSkuCodes.contains(exportSkuCode)){
                    continue;
                }
            }
            if (allSkuMap.get(exportSkuCode)!=null){
                if (allSkuMap.get(exportSkuCode).get(0)!=null){
                    datas.add(allSkuMap.get(exportSkuCode).get(0));
                }
            }
        }


        return datas;
    }

    //编辑盘点范围前查询盘点信息
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public CountScopeInfoDto searchUpdateScope(BigDecimal countScopeId){
        if (countScopeId==null){

        }
        List<String> zoneCodes;
        List<String> locCodes;
        List<String> lotnos;
        List<String> cateCodes;
        List<String> skuCodes;
        InvCountScope countScope = invCountScopeMapper.selectOne(new QueryWrapper<InvCountScope>().eq("INV_COUNT_SCOPE_ID", countScopeId));
        CountScopeInfoDto dto=new CountScopeInfoDto();
        dto.setCountScopId(countScopeId);


        if (!STAR.equals(countScope.getArea())){
            zoneCodes = Arrays.asList(countScope.getArea().split(","));
            dto.setZoneCodes(zoneMapper.selectList(new QueryWrapper<Zone>().in("ZONE_CODE",zoneCodes)));
        }else {
            Zone zone=new Zone();
            zone.setZoneCode(STAR);
            dto.setZoneCodes(Arrays.asList(zone));
        }

        if (!STAR.equals(countScope.getLoc())){
            locCodes = Arrays.asList(countScope.getLoc().split(","));
            dto.setLocCodes(locationMapper.selectList(new QueryWrapper<Location>().in("LOC_CODE",locCodes)));
        }else {
            Location loc=new Location();
            loc.setLocCode(STAR);
            dto.setLocCodes(Arrays.asList(loc));
        }

        if (countScope.getLotNo()!=null){
            if (!STAR.equals(countScope.getLotNo())){
                lotnos = Arrays.asList(countScope.getLotNo().split(","));
                dto.setLotnos(lotnoMapper.selectList(new QueryWrapper<Lotno>().in("LOTNO",lotnos)));
            }else {
                Lotno lotno=new Lotno();
                lotno.setLotno(STAR);
                dto.setLotnos(Arrays.asList(lotno));
            }
        }

        if (!STAR.equals(countScope.getSkuCategory())){
            cateCodes = Arrays.asList(countScope.getSkuCategory().split(","));
            dto.setCateCodes(skuCateMapper.selectList(new QueryWrapper<SkuCate>().in("SKU_CATE_CODE",cateCodes)));
        }else {
            SkuCate skuCate=new SkuCate();
            skuCate.setSkuCateCode(STAR);
            dto.setCateCodes(Arrays.asList(skuCate));
        }

        if (!STAR.equals(countScope.getSku())){
            skuCodes = Arrays.asList(countScope.getSku().split(","));
            dto.setSkuCodes(skuMapper.selectList(new QueryWrapper<Sku>().in("SKU_CODE",skuCodes)));
        }else {
            Sku sku=new Sku();
            sku.setSkuCode(STAR);
            dto.setSkuCodes(Arrays.asList(sku));
        }



        return dto;
    }


    //保存盘点范围(新增/更新)
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<String> saveCountScope(CountScopeDto dto,
                                         HttpServletRequest servletRequest) throws Exception {
        BigDecimal countScopeId = dto.getCountScopId();
        BigDecimal countHeaderId=dto.getCountHeaderId();
        if (countHeaderId==null){
            Shift.fatal("请先保存盘点基本信息!");
        }

        String loginName=HttpSessionUtil.getLoginName(servletRequest);
        Date nowDate=new Date();

        InvCountHeader coutHeader = invCountHeaderMapper.
                selectOne(new QueryWrapper<InvCountHeader>().eq("INV_COUNT_HEADER_ID", countHeaderId));
        if (coutHeader==null){
            Shift.fatal("请先保存盘点单头信息!");
        }
        if (!coutHeader.getStatus().equals(InvHeaderStatusEnum.CREATE.code)&&!coutHeader.getStatus().equals(InvHeaderStatusEnum.APPROVED.code)){
            Shift.fatal("非新建/审核的盘点单无法选择盘点范围!");
        }
        if (dto.getWhsId()==null){
            Shift.fatal("仓库为空!");
        }
        if (!dto.getWhsId().equals(coutHeader.getWhsId())){
            Shift.fatal("请先保存盘点单头信息!");
        }

        List<String> zoneCodes = dto.getZoneCodes();
        List<String> locCodes = dto.getLocCodes();
        List<String> lotnos = dto.getLotnos();
        List<String> cateCodes = dto.getCateCodes();
        List<String> skuCodes = dto.getSkuCodes();

        String zoneStr=null;
        String locStr=null;
        String lotnoStr=null;
        String cateStr=null;
        String skuStr=null;

        if (CollectionUtil.isEmpty(zoneCodes)){
            Shift.fatal("库区不能为空!");
        }
        if (CollectionUtil.isEmpty(locCodes)){
            Shift.fatal("库位不能为空!");
        }
        if (CollectionUtil.isEmpty(cateCodes)){
            Shift.fatal("物料分类不能为空!");
        }
        if (CollectionUtil.isEmpty(skuCodes)){
            Shift.fatal("物料编码不能为空!");
        }
        if (zoneCodes.get(0).equals("-1")){
            zoneCodes=Arrays.asList(STAR);
        }
        if (locCodes.get(0).equals("-1")){
            locCodes=Arrays.asList(STAR);
        }
        if (cateCodes.get(0).equals("-1")){
            cateCodes=Arrays.asList(STAR);
        }
        if (skuCodes.get(0).equals("-1")){
            skuCodes=Arrays.asList(STAR);
        }
        int zoneDisSize = zoneCodes.stream().distinct().collect(Collectors.toList()).size();
        int locDisSize = locCodes.stream().distinct().collect(Collectors.toList()).size();
        int cateDisSize = cateCodes.stream().distinct().collect(Collectors.toList()).size();
        int skuDisSize = skuCodes.stream().distinct().collect(Collectors.toList()).size();
        if (zoneCodes.size()!=zoneDisSize){
            Shift.fatal("库区不能重复!");
        }
        if (locCodes.size()!=locDisSize){
            Shift.fatal("库位不能重复!");
        }
        if (cateCodes.size()!=cateDisSize){
            Shift.fatal("物料分类不能重复!");
        }
        if (skuCodes.size()!=skuDisSize){
            Shift.fatal("物料编码不能重复!");
        }

        if (!CollectionUtil.isEmpty(lotnos)){
            int lotnoDisSize = lotnos.stream().distinct().collect(Collectors.toList()).size();
            if (lotnos.size()!=lotnoDisSize){
                Shift.fatal("批次号不能重复!");
            }
            if (lotnos.get(0).equals("-1")){
                lotnos=Arrays.asList(STAR);
            }
            if (STAR.equals(lotnos.get(0))){
                lotnoStr=lotnos.get(0);
            }else {
                lotnoStr=String.join(",", lotnos);
            }
        }
        zoneStr=String.join(",", zoneCodes);
        locStr=String.join(",", locCodes);
        cateStr=String.join(",", cateCodes);
        skuStr=String.join(",", skuCodes);

        InvCountScope scope=new InvCountScope();
        scope.setInvCountHeaderId(countHeaderId);
        scope.setInvCountScopeId(countScopeId);
        scope.setArea(zoneStr);
        scope.setLoc(locStr);
        scope.setLotNo(lotnoStr);
        scope.setSkuCategory(cateStr);
        scope.setSku(skuStr);
        //新增前查询是否重复
/*        QueryWrapper<InvCountScope> distinctQuery = new QueryWrapper<>();
        distinctQuery.eq("LOC",locStr);
        if (lotnoStr!=null){
            distinctQuery.eq("LOT_NO",lotnoStr);
        }else {
            distinctQuery.isNull("LOT_NO");
        }
        distinctQuery.eq("SKU_CATEGORY",cateStr);
        distinctQuery.eq("SKU",skuStr);
        distinctQuery.eq("AREA",zoneStr);
        if (countScopeId!=null){
            distinctQuery.ne("distinctQuery",countScopeId);
        }*/
        List<InvCountScope> distinctScopes = invCountScopeMapper.selectScopes(zoneStr,locStr,
                lotnoStr,cateStr,skuStr,countHeaderId);
        if (distinctScopes!=null&&distinctScopes.size()>0){
            Shift.fatal("新增盘点范围重复！");
        }
        if (countScopeId==null){

            scope.setCreateTime(nowDate);
            scope.setCreateUser(loginName);
            invCountScopeMapper.insert(scope);
        }else {
            scope.setModifyTime(nowDate);
            scope.setModifyUser(loginName);
            invCountScopeMapper.updateById(scope);
        }

        return new Result<>("保存盘点范围成功!");
    }

    //删除盘点范围
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<String> deleteScope(BigDecimal scopeId,BigDecimal headerId) throws Exception {
        List<Integer> statusList=Arrays.asList(InvHeaderStatusEnum.CREATE.code,InvHeaderStatusEnum.APPROVED.code);
        InvCountHeader header = invCountHeaderMapper.
                selectOne(new QueryWrapper<InvCountHeader>().eq("INV_COUNT_HEADER_ID", headerId));
        if (!statusList.contains(header.getStatus())){
            Shift.fatal("仅["+InvHeaderStatusEnum.CREATE.enumName+"/"+InvHeaderStatusEnum.APPROVED.enumName+
                    "]能删除!");
        }
        invCountScopeMapper.delete(new QueryWrapper<InvCountScope>().eq("INV_COUNT_SCOPE_ID",scopeId));

        return new Result<>("删除盘点范围成功!");
    }

    //审核
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<String> appr(List<BigDecimal> headerIds,HttpServletRequest servletRequest){
        List<InvCountHeader> headerList = invCountHeaderMapper.
                selectList(new QueryWrapper<InvCountHeader>().in("INV_COUNT_HEADER_ID", headerIds));
        List<Integer> statusList = headerList.stream().map(t -> t.getStatus()).distinct().collect(Collectors.toList());
        if (statusList.size()>1){
            Shift.fatal("仅["+InvHeaderStatusEnum.CREATE.enumName+"]的盘点单能审核!");
        }
        if (!statusList.get(0).equals(InvHeaderStatusEnum.CREATE.code)){
            Shift.fatal("仅["+InvHeaderStatusEnum.CREATE.enumName+"]的盘点单能审核!");
        }
        invCountHeaderMapper.updateHeaderStatus(HttpSessionUtil.getLoginName(servletRequest),
                InvHeaderStatusEnum.APPROVED.code,headerIds);
        return new Result<>("审核成功!");
    }

    //废弃
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<String> cancel(List<BigDecimal> headerIds,HttpServletRequest servletRequest){
        List<InvCountHeader> headerList = invCountHeaderMapper.
                selectList(new QueryWrapper<InvCountHeader>().in("INV_COUNT_HEADER_ID", headerIds));
        List<Integer> statusList = headerList.stream().map(t -> t.getStatus()).distinct().collect(Collectors.toList());
        if (statusList.size()>1){
            Shift.fatal("仅["+InvHeaderStatusEnum.CREATE.enumName+"]的盘点单能废弃!");
        }
        if (!statusList.get(0).equals(InvHeaderStatusEnum.CREATE.code)){
            Shift.fatal("仅["+InvHeaderStatusEnum.CREATE.enumName+"]的盘点单能废弃!");
        }
        invCountHeaderMapper.updateHeaderStatus(HttpSessionUtil.getLoginName(servletRequest),
                InvHeaderStatusEnum.CANCEL.code,headerIds);
        return new Result<>("废弃成功!");
    }

    //取消审核
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<String> cancelAppr(List<BigDecimal> headerIds,HttpServletRequest servletRequest){
        List<InvCountHeader> headerList = invCountHeaderMapper.
                selectList(new QueryWrapper<InvCountHeader>().in("INV_COUNT_HEADER_ID", headerIds));
        List<Integer> statusList = headerList.stream().map(t -> t.getStatus()).distinct().collect(Collectors.toList());
        if (statusList.size()>1){
            Shift.fatal("仅["+InvHeaderStatusEnum.APPROVED.enumName+"]的盘点单能取消审核!");
        }
        if (!statusList.get(0).equals(InvHeaderStatusEnum.APPROVED.code)){
            Shift.fatal("仅["+InvHeaderStatusEnum.APPROVED.enumName+"]的盘点单能取消审核!");
        }
        invCountHeaderMapper.updateHeaderStatus(HttpSessionUtil.getLoginName(servletRequest),
                InvHeaderStatusEnum.CREATE.code,headerIds);
        return new Result<>("取消审核成功!");
    }

    //关闭
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<String> closeHeader(List<BigDecimal> headerIds,HttpServletRequest servletRequest){
        List<InvCountHeader> headerList = invCountHeaderMapper.
                selectList(new QueryWrapper<InvCountHeader>().in("INV_COUNT_HEADER_ID", headerIds));
        List<Integer> statusList = headerList.stream().map(t -> t.getStatus()).distinct().collect(Collectors.toList());
        if (statusList.size()>1){
            Shift.fatal("仅["+InvHeaderStatusEnum.FINISH_DIVERSITY.enumName+"]的盘点单能关闭!");
        }
        if (!statusList.get(0).equals(InvHeaderStatusEnum.FINISH_DIVERSITY.code)){
            Shift.fatal("仅["+InvHeaderStatusEnum.FINISH_DIVERSITY.enumName+"]的盘点单能关闭!");
        }
        invCountHeaderMapper.updateHeaderStatus(HttpSessionUtil.getLoginName(servletRequest),
                InvHeaderStatusEnum.CLOSE.code,headerIds);
        return new Result<>("关单成功!");
    }

    //结果送审
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<String> sendApr(List<BigDecimal> headerIds,HttpServletRequest servletRequest){
        List<InvCountHeader> headerList = invCountHeaderMapper.
                selectList(new QueryWrapper<InvCountHeader>().in("INV_COUNT_HEADER_ID", headerIds));
        List<Integer> statusList = headerList.stream().map(t -> t.getStatus()).distinct().collect(Collectors.toList());
/*        if (statusList.size()>2){
            Shift.fatal("仅["+InvHeaderStatusEnum.FINISH_INV.enumName+"/"+InvHeaderStatusEnum.FINISH_REL_INV.enumName+"]的盘点单能送审!");
        }*/

        for (Integer status : statusList) {
            if (status.equals(InvHeaderStatusEnum.FINISH_INV.code)||status.equals(InvHeaderStatusEnum.FINISH_REL_INV.code)||
                    status.equals(InvHeaderStatusEnum.RESULT_FAIL_APPROVED.code)){
                continue;
            }
            Shift.fatal("仅["+InvHeaderStatusEnum.FINISH_INV.enumName+"/"+InvHeaderStatusEnum.FINISH_REL_INV.enumName+"/"+InvHeaderStatusEnum.RESULT_FAIL_APPROVED.enumName+"]的盘点单能送审!");
        }
        invCountHeaderMapper.updateHeaderStatus(HttpSessionUtil.getLoginName(servletRequest),
                InvHeaderStatusEnum.RESULT_WAIT_APPROVED.code,headerIds);
        return new Result<>("送审成功!");
    }







}
